import { isRef, onBeforeUnmount, onMounted, unref, watchEffect } from "vue";

/**
 * 给document绑定一个点击事件。
 *    排除掉某些元素之外
 */
export function useClickOutside(target, callback) {
  function onHandle(event) {
    console.log("onHandle");

    const newTarget = unref(target);

    // 判断
    if (newTarget && newTarget.contains(event.target)) {
      return;
    }

    callback(event);
  }

  if (isRef(target)) {
    watchEffect(() => {
      console.log("watchEffect");

      const newTarget = unref(target);

      // 自动收集依赖，默认会触发一次
      document.addEventListener("click", onHandle, true);

      return () => {
        console.log("watchEffect - 清理");
        document.removeEventListener("click", onHandle, true);
      };
    });
  } else {
    onMounted(() => {
      document.addEventListener("click", onHandle, true);
    });

    onBeforeUnmount(() => {
      document.removeEventListener("click", onHandle, true);
    });
  }
}
